package com.jiukuaidao.zhulin.module.shoppingcart;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiukuaidao.library.base.BaseActivity;
import com.jiukuaidao.library.common.AppManager;
import com.jiukuaidao.library.common.dialog.CommDialog;
import com.jiukuaidao.library.common.dialog.ICallBack;
import com.jiukuaidao.library.util.DBUtils;
import com.jiukuaidao.library.util.ImageGlideUtils;
import com.jiukuaidao.library.util.ToastUtil;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiConfirmOrderInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo;
import com.jiukuaidao.zhulin.entity.ApiShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.DBShoppingCartInfo;
import com.jiukuaidao.zhulin.entity.EventShoppingCardFailed;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.address.AddressManagerActivity;
import com.jiukuaidao.zhulin.module.home.MainActivity;
import com.jiukuaidao.zhulin.module.order.ConfirmOrderActivity;
import com.jiukuaidao.zhulin.util.ShopInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author : BinarySatan
 * Date : 2016/6/7
 * Description :
 */
public class ShoppingCartActivity extends BaseActivity<ShoppingCartContract.Presenter> implements ShoppingCartContract.View, CommContract.ShoppingCartNetView, CommContract.ShoppingCartLocalView {
    @BindView(R.id.titile_left_imageview)
    ImageView mTitileLeftImageview;
    @BindView(R.id.titile_text)
    TextView mTitileText;
    @BindView(R.id.titile_right_text)
    TextView mTitileRightText;

    @BindView(R.id.tv_receipt_address)
    TextView mTvReceiptAddress;
    @BindView(R.id.tv_receipt_phone_number)
    TextView mTvReceiptPhoneNumber;
    @BindView(R.id.tv_receipt_name)
    TextView mTvReceiptName;
    @BindView(R.id.iv_receipt_arrow)
    ImageView mIvReceiptArrow;
    @BindView(R.id.tv_clean)
    TextView mTvClean;
    @BindView(R.id.et_remark_info)
    EditText mEtRemarkInfo;
    @BindView(R.id.cb_invoice)
    CheckBox mCbInvoice;
    @BindView(R.id.et_invoice)
    EditText mEtInvoice;

    @BindView(R.id.rl_address)
    RelativeLayout mRLAddress; //收货地址布局.

    @BindView(R.id.receipt_address)
    TextView mReceiptAddress; //收货地址
    @BindView(R.id.rl_selected_address)
    RelativeLayout mRLSelectedAddress;//已选地址布局

    @BindView(R.id.total_price)
    TextView mTvTotalPrice; //购物车总价格
    @BindView(R.id.total_count)
    TextView mTvFullShipmentFree; //满多少免配送费
    @BindView(R.id.tv_confirm_order)
    TextView mTvSettlement; //去结算

    @BindView(R.id.footer)
    RelativeLayout mFooter; //底部结算栏

    @BindView(R.id.tv_empty)
    TextView mTvEmpty; //空购物车 显示

    @BindView(R.id.sv)
    ScrollView mSV;

    @BindView(R.id.ll_dynamic_shoppingcart_goods)
    LinearLayout mLLDynamicShoppingCartGoods; //动态添加购物车商品信息


    private String mFullShipmentFree = "0"; //满多少免配送费
    private String mStartPrice; //起送价
    private String mDeliveryPrice;//配送费

    private String mShopId;
    private String mGoodsNumber;  //商品sn号
    private String mGoodsCurPrice; //当前操作商品的价钱
    private ApiHistoryAddressInfo.AddressInfo mAddressInfo;  //地址信息

    private List<EventShoppingCartInfo> mEventShoppingCartDatas; // 购物车数据字段
    private ApiShoppingCartInfo mShoppingCartDatas; //服务器返回的购物车数据
    private CommPresenter mCommPresenter;

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_shoppingcart;
    }

    @Override
    protected void handleBundle(Bundle bundle) {

        mFullShipmentFree = bundle.getString("fullShipmentFree");//满多少免配送费
        mStartPrice = bundle.getString("startPrice"); //起送价
        mDeliveryPrice = bundle.getString("deliveryPrice");//配送费--其实没用

    }


//    @Override
//    protected void onStart() {
//        super.onStart();
//        mCommPresenter.getShoppingCartDataLocal();
//    }

    @Override
    protected void init() {

        new ShoppingPresenter(TaskProvider.provideTasksRepository(this), this);

        EventBus.getDefault().register(this);
        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(this), this);
        mShopId = ShopInfoUtil.getShopId();
        mTitileText.setText(getString(R.string.shoppingcart));
        mTvSettlement.setText(getString(R.string.settlement));

        mTvFullShipmentFree.setText(String.format(getString(R.string.full_shipment_free),
                mFullShipmentFree)); //满多少免配送费


        mCbInvoice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                    mEtInvoice.setVisibility(View.VISIBLE);
                else
                    mEtInvoice.setVisibility(View.GONE);
            }
        });

        //加载购物车数据
        mCommPresenter.getShoppingCartDataLocal();
    }


    private void setShoppingCartViewVisible(boolean isEmpty) {
        if (isEmpty) {
            mSV.setVisibility(View.GONE);
            mFooter.setVisibility(View.GONE);
            mTvEmpty.setVisibility(View.VISIBLE);
        } else {
            mSV.setVisibility(View.VISIBLE);
            mFooter.setVisibility(View.VISIBLE);
            mTvEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 从网络获取购物车数据失败 ( 一般为没有商品了)
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventShoppingCardDataNetFailed(EventShoppingCardFailed data) {
        setShoppingCartViewVisible(true);
    }

    /**
     * 获取本地购物车后的回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventShoppingCartDataLocal(List<EventShoppingCartInfo> eventShoppingCartDatas) {

        showLoading(null);
        mEventShoppingCartDatas = eventShoppingCartDatas;
        mCommPresenter.getShoppingCartDataNet();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventConfirmOrder(ApiConfirmOrderInfo info){

//        Log.i("wangyijie", "onEventConfirmOrder:  --------------------------"  + info.orderNo);
        mCommPresenter.getShoppingCartDataLocal();

    }

    /**
     * 选择地址后回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventAddressResult(ApiHistoryAddressInfo.AddressInfo data) {

        if (data == null)
            return;

        mShopId = data.shopId; //店铺id
        mAddressInfo = data; //地址信息

        mReceiptAddress.setVisibility(View.GONE);
        mRLSelectedAddress.setVisibility(View.VISIBLE);
        mTvReceiptAddress.setText(data.address);
        mTvReceiptPhoneNumber.setText(data.mobile);
        mTvReceiptName.setText(data.consignee);
        //获取本地购物车数据,获取成功后, 在去联网
        mCommPresenter.getShoppingCartDataLocal();
    }

    @Override
    public void getShoppingCartDataNetSuc(ApiShoppingCartInfo shoppingCartData) {
        if (shoppingCartData == null) return;
        // 设置购物车页控件显隐
        setShoppingCartViewVisible(false);


        mShoppingCartDatas = shoppingCartData;

        mTvTotalPrice.setText(String.valueOf(shoppingCartData.goodsAmount)); //商品总额


        //是否满足起送费
        if (mPresenter.isAreOverStartPrice()) {
            mTvSettlement.setClickable(true);
            mTvSettlement.setBackgroundColor(ContextCompat.getColor(this, R.color.color_fa515a));
        } else {
            //TODO 记得取消屏蔽~
            mTvSettlement.setClickable(false);
            mTvSettlement.setBackgroundColor(ContextCompat.getColor(this, R.color.text_gray_999999));
        }

        dynamicAddGoodsInfo(shoppingCartData.items);

        hideLoading();
    }


    /**
     * 动态添加商品信息
     *
     * @param items 信息数据
     */
    private void dynamicAddGoodsInfo(List<ApiShoppingCartInfo.ItemsBean> items) {

        if (mLLDynamicShoppingCartGoods.getChildCount() != 0)
            mLLDynamicShoppingCartGoods.removeAllViews();


        for (int i = 0; i < items.size(); i++) {
            final ApiShoppingCartInfo.ItemsBean item = items.get(i);
            final String price = item.price;
            View view = LayoutInflater.from(this).inflate(R.layout.dynamic_shoppingcart_goods_detail, new FrameLayout(this), false);
            ImageView picture = (ImageView) view.findViewById(R.id.iv_goods_picture);
            TextView name = (TextView) view.findViewById(R.id.tv_goods_name);
            TextView tvPrice = (TextView) view.findViewById(R.id.tv_goods_price);
            TextView count = (TextView) view.findViewById(R.id.tv_goods_count);
            ImageView addGoods = (ImageView) view.findViewById(R.id.iv_goods_add);
            ImageView reduceGoods = (ImageView) view.findViewById(R.id.iv_goods_reduce);
            RelativeLayout mRLAddRecudeLayout = (RelativeLayout) view.findViewById(R.id.rl_add_reduce_layout);

            ImageView invalidDelete = (ImageView) view.findViewById(R.id.iv_invalid_delete);
            if (!item.valid) {  // 商品无效6,切换地址引起.
                invalidDelete.setVisibility(View.VISIBLE);
                mRLAddRecudeLayout.setVisibility(View.GONE);
                picture.setImageResource(R.mipmap.ic_default_goods_list);
                name.setTextColor(ContextCompat.getColor(this, R.color.color_999999));
                tvPrice.setTextColor(ContextCompat.getColor(this, R.color.color_999999));
            } else { //商品有效~
                ImageGlideUtils.GlideImages(this, item.picture, picture, R.mipmap.ic_default_goods_list);
                count.setText(String.valueOf(item.count));
            }

            name.setText(item.name);
            tvPrice.setText(String.format(getString(R.string.rmb_symbol), price));


            if (i == items.size() - 1)
                view.findViewById(R.id.line2).setVisibility(View.GONE);

            //加商品
            addGoods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGoodsNumber = item.gn;
                    mGoodsCurPrice = item.price;
                    mCommPresenter.addShoppingCartLocal();
                }
            });
            //减商品
            reduceGoods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGoodsNumber = item.gn;
                    mCommPresenter.reduceShoppingCartLocal();
                }
            });

            //无效商品, 点击删除.
            invalidDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mGoodsNumber = item.gn;
                    DBUtils.deleteAll(DBShoppingCartInfo.class, CommPresenter.mFindKey, mGoodsNumber);
                    mCommPresenter.getShoppingCartDataLocal();
                }
            });

            mLLDynamicShoppingCartGoods.addView(view);
        }
    }

    @OnClick(R.id.titile_left_imageview)
    public void clickBack() {
        if (mReceiptAddress.getVisibility() != View.VISIBLE) {
            AppManager.getAppManager().finishActivityExcept(MainActivity.class);
            return;
        }

        this.finish();
    }

    @Override
    public void onBackPressed() {
        clickBack();
    }

    @OnClick(R.id.tv_confirm_order)
    public void clickSettlement() {

        if (mAddressInfo == null) {
            ToastUtil.show("地址不能为空", Toast.LENGTH_SHORT);
            return;
        }

        Bundle b = new Bundle();
        b.putSerializable("addressInfo", mAddressInfo);
        b.putString("invoice", mEtInvoice.getText().toString().trim());
        b.putString("remark", mEtRemarkInfo.getText().toString().trim());
        intentJump(ConfirmOrderActivity.class, b);
    }


    /**
     * 点击收货地址
     */
    @OnClick(R.id.rl_address)
    public void clickReceiptAddress() {
        Bundle bundle = new Bundle();
        bundle.putString("fromActivity", "shopCart");
        intentJump(AddressManagerActivity.class, bundle);
    }

    /**
     * 清空购物车
     */
    @OnClick(R.id.tv_clean)
    public void clickClean() {
        showDialogTwoBtn(getString(R.string.confirm_clean_shoppingcart), new ICallBack.TwoCallBack() {
            @Override
            public void left(CommDialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void right(CommDialog dialog) {
                dialog.dismiss();
                DBUtils.deleteAll(DBShoppingCartInfo.class);
                mCommPresenter.getShoppingCartDataLocal();
            }
        });

    }

    @Override
    public String getGoodsCurPrice() {
        return mGoodsCurPrice;
    }

    @Override
    public String getGoodsNumber() {
        return mGoodsNumber;
    }

    @Override
    public List<EventShoppingCartInfo> getEventShoppingCartDatas() {
        return mEventShoppingCartDatas;
    }

    @Override
    public String getShopId() {
        return mShopId;
    }

    @Override
    public ApiShoppingCartInfo getShoppingCartDatas() {
        return mShoppingCartDatas;
    }

    @Override
    public String getStartPrice() {
        return mStartPrice;
    }

    @Override
    public String getTotalPrice() {
        return mTvTotalPrice.getText().toString().trim();
    }
}
